const mdutil = require('utils')

function PDDSDK(options) {
  if (!(this instanceof PDDSDK)) {
    return new PDDSDK(options)
  }
  options = options || {}

  if (!options.appKey || !options.secretKey) {
    throw new Error('appKey and secretKey are necessary!')
  }

  this.appKey = options.appKey
  this.secretKey = options.secretKey
  this.endpoint = options.endpoint || 'https://gw-api.pinduoduo.com/api/router'
  this.api={
    "search": "pdd.ddk.goods.search",
    "queryCoupon": "pdd.ddk.coupon.info.query",
    'detail':'pdd.ddk.goods.detail',
    'url':'pdd.ddk.goods.promotion.url.generate',
    'qrcode':'pdd.ddk.weapp.qrcode.url.gen',
    'rank':'pdd.ddk.top.goods.list.query',//爆款
    'theme':'pdd.ddk.theme.goods.search',
    'reward':'pdd.ddk.rp.prom.url.generate',//红包
    'lottery':'pdd.ddk.lottery.url.gen',//转盘
    'theme_url':'pdd.ddk.theme.prom.url.generate',//主题链接
    'changeurl':'pdd.ddk.goods.zs.unit.url.gen',//转换
    'allorder':'pdd.ddk.all.order.list.increment.get',
    'orderlist':'pdd.ddk.order.list.range.get',
    'order': 'pdd.ddk.order.detail.get',
    'mallurl':'pdd.ddk.mall.url.gen',
    'shop':'pdd.ddk.merchant.list.get',
    'kouling':'pdd.ddk.phrase.generate',
    'cate':'pdd.goods.opt.get'
  }
}

PDDSDK.prototype.request = function (params) {
  const { method, ...rest } = params

  const args = {

    client_id: this.appKey,
    // param_json: JSON.stringify(rest),
    // sign_method: 'md5',
    data_type: 'JSON',
    timestamp: this.timestamp(),
    v: "V1",
    'type': method,
   
  }  
  var obj2 = Object.assign(args,rest);
  obj2.sign = this.sign(obj2);

  return new Promise((resolve, reject) => {
    const err = mdutil.checkRequired(params, 'method')
    if (err) {
      reject(err)
    }

    wx.request({
      url: this.endpoint,
      method: 'POST',
      data: obj2,
      // header:a,
      success: res => {
    
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {
        
          reject(res);
        }
      },
      fail: e => {
        reject(e)
      }
    })
   
  })
}

PDDSDK.prototype.execute = function (apiname, params) {
  params.method = apiname
  return this.request(params).then((res) => {
    const field = `${apiname.replace(/\./g, '_')}_response`
    if (apiname !='pdd.goods.opt.get'){
      var reg = new RegExp("pdd_ddk_", "g");
    }else{
      var reg = new RegExp("pdd_", "g");
    }
  
    var a = field.replace(reg, "")
    const resp = res[a]
    
    if (resp) {
      return resp
    } else {
      console.log('没有数据')
    }

  })
  // const field = `${apiname.replace(/\./g, '_')}_response`
  // const resp = res[field];
  // console.log("结果 -")
  // console.log(resp)

  // return this.request(params)
}

PDDSDK.prototype.sign = function (params) {
  var sorted = Object.keys(params).sort()
  var basestring = this.secretKey

  for (var i = 0, l = sorted.length; i < l; i++) {
    var k = sorted[i]
    basestring += k +params[k]
    

  }
  // console.log(params)

  basestring += this.secretKey

  return mdutil.md5(basestring).toUpperCase()
}
PDDSDK.prototype.notEmpty=function(obj) {
  // 检验 undefined 和 null 参数检测
  if (!obj || obj == '' || obj == undefined) { return false; }
  if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) { return false; }
  if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) { return false; }
  return true;
}
PDDSDK.prototype.funcWhere=function(){
  var errs = new Error().stack
  console.log(errs)
  var names = new Error().stack.match(/at (.*?) /g);
  var name = names[1].replace('at Object.', '').trim();
  return name;
}
var D = ['search', 'queryCoupon','detail','url','qrcode','cate']
for (var i = 0; i < D.length; i++) {
  !function (e) {

    PDDSDK.prototype[e] = function (data={}) {
      var method = this.api[e]
   
      if (method){
        return this.execute(method,data)
      }

    };

  }(D[i])

}
PDDSDK.prototype.timestamp = function (d, options) {
  d = d || new Date()
  var timestamp = d.getTime();

  return timestamp;
}

module.exports = PDDSDK
